package com.heisenhub.file.domin.impl;


import com.heisenhub.file.common.dto.FileDto;
import com.heisenhub.file.domin.FileStorageService;
import com.heisenhub.file.entity.OpFile;
import com.heisenhub.file.enums.FileStatusEnum;
import com.heisenhub.file.utils.FileUtils;
import com.heisenhub.file.utils.MinioClientUtils;
import com.heisnenhub.common.module.exception.RRException;
import com.heisnenhub.common.module.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author sen
 * @description
 * @date 2024/2/27 15:48
 */
@Slf4j
@Service
@ConditionalOnProperty(value = "file.service.name", havingValue = "minio",matchIfMissing = true)
public class MinioFileStorageService implements FileStorageService {

    @Autowired
    private MinioClientUtils minioClientUtils;



    @Override
    public List<OpFile> upload(MultipartFile[] files , FileDto fileDto) {
        log.info("【minio 文件上传】");
        List<OpFile> fileUrlList = new ArrayList<>();
        for (MultipartFile file : files) {

            String originalFilename = file.getOriginalFilename();
            //获取文件拓展名
            String extName = FileUtils.extName(originalFilename);
            log.info("文件拓展名:" + extName);
            //            生成新的文件名，存入到minio
          //  long millSeconds = Instant.now().toEpochMilli();
            String ymdhms = TimeUtils.nowDateStr();
            String minioFileName = ymdhms +"-"+ RandomStringUtils.randomNumeric(12) + "." + extName;
            String fileName = minioFileName;
            String folderName = fileDto.getFolderName();
            if(folderName !=null)  minioFileName = folderName+ "/"+ minioFileName;

            String contentType = file.getContentType();
            log.info("文件mime:{}", contentType);
            //            返回文件大小,单位字节
            long size = file.getSize();
            log.info("文件大小：" + size);
            try {
               // String bucketName = minioConfig.getBucketName();
                String bucketName = fileDto.getStoreService();
                minioClientUtils.makeBucket(bucketName);
                minioClientUtils.putObject(bucketName, file, minioFileName);

                // 文件对象
                OpFile opFile = new OpFile();
                opFile.setOriginalName(originalFilename);
                opFile.setFolderName(StringUtils.isNoneEmpty(folderName)?folderName:bucketName);
                opFile.setCreatetime(TimeUtils.nowDate());
                opFile.setStoreService(bucketName);
                opFile.setStatus(FileStatusEnum.SUCCESS.getStatus());
                opFile.setStorePath(minioFileName) ;
                opFile.setFileName(fileName);
                opFile.setSize(size);
               // String fileUrl = fileUrl(bucketName, minioFileName);

                fileUrlList.add(opFile);


            } catch (Exception e) {
                log.error("上传{}文件出错:{}",originalFilename, e);
                throw new RRException("上传"+originalFilename+"文件出错" );

            }
        }

        return fileUrlList;
    }

    @Override
    public String fileUrl(String bucketName, String fileName) {
        log.info("【获取文件 url】 bucketName:{} fileName:{}",bucketName,fileName);
        try {
            return   minioClientUtils.getPresignedObjectUrl(bucketName, fileName, 24 * 3600);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException("获取文件"+fileName+" url失败" );
        }

    }

    @Override
    public void delete(String bucketName, String fileName) {
        log.info("【文件删除】 bucketName:{} fileName:{}",bucketName,fileName);
        try {
            minioClientUtils.removeObject(bucketName,fileName);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException("删除"+fileName+"文件失败" );
        }
    }

    @Override
    public void download(String bucketName, String fileName, HttpServletResponse response) {
        log.info("【文件下载】 bucketName:{} fileName:{}",bucketName,fileName);
        minioClientUtils.downloadFile(bucketName,fileName,null,response);
    }
}
